<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Call\Action\Dashboard;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Logic\RecordIndexLogic;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\App\Sales\Contract\CallRecordContract;
use MoChat\App\Sales\Contract\SalesClientTaskContract;
use MoChat\App\Sales\Model\CallRecord;
use Hyperf\Di\Annotation\Inject;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 呼叫记录导出.
 * @Controller
 */
class RecordExport extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var CallRecordContract
     */
    protected CallRecordContract $callRecordService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * 
     * @RequestMapping(path="/dashboard/call/recordExport", methods="GET")
     */
    public function handle(): array
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        // 请求参数
        $params = $this->request->inputs(
            ['callerNumber', 'destNumber', 'callType', 'startTime', 'endTime','page', 'perPage'],
            ['page' => 1, 'perPage' => 10]
        );
        // 校验参数
        $this->validated($params);
        $where = [];
        //时间筛选
        if (!empty($params['startTime']) && !empty($params['endTime'])){
            $where[] = ['created_time', '>=', $params['startTime']];
            $where[] = ['created_time', '<', $params['endTime']];
        }
        //主叫模糊匹配
        if (!empty($params['callerNumber'])){
            $where[] = ['caller_id_number', 'like','%'.$params['callerNumber'].'%'];
        }
        //被叫模糊匹配
        if (!empty($params['callerNumber'])){
            $where[] = ['destination_number', 'like','%'.$params['destNumber'].'%'];
        }
        //呼叫类型
        if (!empty($params['callType'])){
            $where[] = ['call_type','=' ,$params['callType']];
        }
        $list=$this->callRecordService->getListAll($where,['*']);
        return $this->processingToTal($list);
    }
    /**
     * 组装基础数据
     * @param $tags
     * @return array
     */
    private function processingToTal($tags): array
    {
        $url = '';
        if (!empty($tags)) {
            $newExcel = new Spreadsheet();  //创建一个新的excel文档
            $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
            $objSheet->setTitle('管理员表');  //设置当前sheet的标题

            //设置宽度为true,不然太窄了
            $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);

            //设置第一栏的标题
            $objSheet->setCellValue('A1', '主叫号码')
                ->setCellValue('B1', '被叫号码')
                ->setCellValue('C1', '类型')
                ->setCellValue('D1', '通话创建时间')
                ->setCellValue('E1', '接通时间')
                ->setCellValue('F1', '通话时常')
                ->setCellValue('G1', '呼叫原因');

            //第二行起，每一行的值,setCellValueExplicit是用来导出文本格式的。
            //->setCellValueExplicit('C' . $k, $val['admin_password']PHPExcel_Cell_DataType::TYPE_STRING),可以用来导出数字不变格式
            foreach ($tags as $k => $tag) {
                $k = $k + 2;
                $callType='';
                if ($tag['callType']=='out'){
                    $callType='呼出';
                }
                if ($tag['callType']=='in'){
                    $callType='呼入';
                }
                if ($tag['callType']=='voiceMail'){
                    $callType='语音信箱';
                }
                $totalSeconds=$tag['callDuration'];
                $time=$totalSeconds;
                if ($totalSeconds){
                    //小时
                    $hour=floor($totalSeconds/3600);
                    $hourSurplusSeconds=$totalSeconds-($hour*3600);
                    //分钟
                    $minutes=floor($hourSurplusSeconds/60);
                    //秒
                    $seconds=$hourSurplusSeconds-($minutes*60);
                    //通话时间
                    $time=$hour.":".$minutes.":".$seconds;
                }
                $objSheet->setCellValue('A' . $k, $tag['callerIdNumber'])
                    ->setCellValue('B' . $k, $tag['destinationNumber'])
                    ->setCellValue('C' . $k, $callType)
                    ->setCellValue('D' . $k, $tag['createdTime'])
                    ->setCellValue('E' . $k, $tag['answeredTime'])
                    ->setCellValue('F' . $k, $time)
                    ->setCellValue('G' . $k, "");
            }
            $url = $this->downloadExcel($newExcel, '呼叫记录', 'Xls');
        }
        return ['url' => $url];
    }

    //公共文件，用来传入xls并下载
    public function downloadExcel($newExcel, $filename, $format)
    {
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

//        $objWriter->save('php://output');
        //通过php保存在本地的时候需要用到
        $url = BASE_PATH . '/storage/upload/static' . '/呼叫记录.xlsx';
        $objWriter->save($url);
        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        //If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        return 'http://manage-cop.sczrk.cn/api/static/呼叫记录.xlsx';
    }
    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'page' => 'integer',
            'perPage' => 'integer',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'page.integer' => '页码必须为整数',
            'perPage.integer' => '页码必须为整数',
        ];
    }
}
